import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { checkPermissionRole } from '@/api/all';
import { clearPending } from '@/utils/request';

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect','/bind'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {

  NProgress.start()

  document.title = getPageTitle(to.meta.title)

  const hasToken = getToken()

  if (hasToken) {
    //判断是否需要缓存
    if(!to.meta.keepAlive) {
      to.meta.keepAlive = false; 
      next()
    }

    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() 
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0

      if (hasRoles) {
        console.log(to.meta.apiPath)
        if(to.meta.apiPath) {

          checkPermissionRole({resources: to.meta.apiPath}).then(res=>{
            const { data } = res
            if(data.data) {
              next()
            } else {
              next({ path: '/error/401' })
            }
          })
        }
      } else {
        try {
          const { roles } = await store.dispatch('user/getInfo')
          store.dispatch('GenerateRoutes', { roles }).then(accessRoutes => {
            router.addRoutes(accessRoutes) 
            next({ ...to, replace: true }) 
          })

        } catch (error) {
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
